package com.mb.ext.core.util;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.mb.ext.core.constant.WechatConstants;
import com.mb.ext.msg.HttpClientHelper;
import com.mb.ext.msg.WXJSONAccessToken;
import com.mb.ext.msg.WXJSONQRCodeTicket;

@Component
public class QRCodeGenerator {
	
	@Autowired
	private PaymentUtil paymentUtil;
	
	@Autowired
	private WXInitializeUtility wxInitializeUtility;

	public String getQRCodeTicket(){
		String token = wxInitializeUtility.getEffectiveToken(paymentUtil.getWechatAppIdOfficialAccount(),paymentUtil.getWechatAppSecretOfficialAccount());
		String url = WechatConstants.URL_QRCODE_TICKET.replace("ACCESS_TOKEN",token);

		String data = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"SCENE_STRING\"}}}";
		data=data.replace("SCENE_STRING", WechatConstants.TOKEN);
		
		String result = HttpClientHelper.postJsonObject(url, data);
	 
		WXJSONQRCodeTicket ticketJson =JSON.parseObject(result,WXJSONQRCodeTicket.class);
		
		System.out.println("Ticket:" + ticketJson.getTicket());
		System.out.println("URL:" + ticketJson.getUrl()); 
		return  ticketJson.getTicket() ;
	}
	
	/**
	 * ��ȡ���ںŶ�ά��
	 * @return
	 * @throws Exception
	 */
	public BufferedImage getQRCode() throws Exception{
		
		String ticket=getQRCodeTicket();
		ticket=java.net.URLEncoder.encode(ticket,"UTF-8");
		String url=WechatConstants.URL_QRCODE.replace("TICKET", ticket);
		
		BufferedImage img= HttpClientHelper.getImageFromURL(url, null); 
	
		return img;
	}

	/**
	 * ��ȡ΢��С������ͼ��--����image����
	 * @throws Exception
	 */
	public BufferedImage getWXAppCodImg(String page, String scene, int width) throws Exception {
		String token = getWXAAccessToken();

		String url = WechatConstants.URL_WXA_CODE;
		url = url.replace("ACCESS_TOKEN", token);

		String data = "{\"scene\": \"SCENE_PARAM\",\"page\": \"PAGE_PARAM\", \"width\": "+width+",\"auto_color\": false,\"line_color\": {\"r\":\"0\",\"g\":\"0\",\"b\":\"0\"}}";
		data=data.replace("SCENE_PARAM",scene);
		data=data.replace("PAGE_PARAM",page);
		BufferedImage img = getWxQRImage(url, data);

		return img;
	}

	/**
	 * ���С������ʵ���ȨACCESS_TOKEN
	 * @return ����token
	 */
	private String getWXAAccessToken(){
//		String APPID = "wxdc6d7dd9b0447f4f";
//		String APPSECRET = "db135ec778df86492ef5eb2c4501f605";
//		String APPID = "wxb70130eabe22bd46";
//		String APPSECRET = "01fbfd6646de5ce1fae6a3597ba14f53";
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + paymentUtil.getWechatAppIdMiniProgram() + "&secret=" + paymentUtil.getWechatAppSecretMiniProgram();

		// ����Token
		String r = HttpClientHelper.sendGet(url, null, "UTF-8");
		WXJSONAccessToken token = JSON.parseObject(r,WXJSONAccessToken.class);
		
		return token.getAccess_token();
	}
	
	static BufferedImage getWxQRImage(String urlParam, String json) {  
        StringBuffer resultBuffer = null;  
     
        HttpURLConnection con = null;  
        OutputStreamWriter osw = null;  
        BufferedReader br = null;  
        BufferedImage bi=null;
        // ��������  
        try {  
            URL url = new URL(urlParam);  
            con = (HttpURLConnection) url.openConnection();  
            con.setRequestMethod("POST");  
            con.setDoOutput(true);  
            con.setDoInput(true);  
            con.setUseCaches(false);  
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
            
            osw = new OutputStreamWriter(con.getOutputStream(), "utf-8");  
            osw.write(json);  
            osw.flush();  
            
            
            con.connect();  
            InputStream is = con.getInputStream();  
//            // ��ȡ��������  
//            resultBuffer = new StringBuffer();  
//            int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));  
//            if (contentLength > 0) {  
//                br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));  
//                String temp;  
//                while ((temp = br.readLine()) != null) {  
//                    resultBuffer.append(temp);  
//                }  
//            }   
            
            bi=ImageIO.read(is);
            
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        } finally {  
            if (osw != null) {  
                try {  
                    osw.close();  
                } catch (IOException e) {  
                    osw = null;  
                    throw new RuntimeException(e);  
                } finally {  
                    if (con != null) {  
                        con.disconnect();  
                        con = null;  
                    }  
                }  
            }  
            if (br != null) {  
                try {  
                    br.close();  
                } catch (IOException e) {  
                    br = null;  
                    throw new RuntimeException(e);  
                } finally {  
                    if (con != null) {  
                        con.disconnect();  
                        con = null;  
                    }  
                }  
            }  
        }  
  
        return bi;  
    }  
	
}
